package com.bysj.lms.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bysj.lms.common.Const;
import com.bysj.lms.controller.LoginController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class JwtUtil {

    public static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    /**
     * @Description  ：生成token
     * @author       : lj
     * @param        : [user]
     * @return       : java.lang.String
     * @exception    :
     */
    public static String sign(String account,long currentTime){

        logger.info("account:"+account);
        logger.info("currentTime:"+currentTime);
        String token=null;
        try {
            Date expireAt=new Date(currentTime+Const.EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("xiaojiakai")//发行人
                    .withClaim(Const.TOKEN_CLAIM_USERNAME,account)//存放数据
                    .withClaim(Const.CURRENT_TIME,currentTime)
                    .withExpiresAt(expireAt)//过期时间
                    .sign(Algorithm.HMAC256(Const.TOKEN_SECRET));
        } catch (IllegalArgumentException|JWTCreationException je) {
            System.out.println("发放token失败");
        }
        return token;
    }


    /**
     * @Description  ：token验证
     * @param        : [token]
     * @return       : java.lang.Boolean
     * @exception    :
     */
    public static void verify(String token, String username) {
        Algorithm algorithm = null;
        try {
            // 根据密码生成JWT效验器
            algorithm = Algorithm.HMAC256(Const.TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).withClaim(Const.TOKEN_CLAIM_USERNAME, username)
                    .build();
            // 效验TOKEN
            verifier.verify(token);
        } catch (SignatureVerificationException exception) {
            throw new SignatureVerificationException(algorithm);
        }catch (TokenExpiredException e){
            throw new TokenExpiredException("token 过期了");
        }
    }



    public static String getAccount(String token){
        try{
            DecodedJWT decodedJWT=JWT.decode(token);
            return decodedJWT.getClaim(Const.TOKEN_CLAIM_USERNAME).asString();

        }catch (JWTCreationException e){
            return null;
        }
    }
    public static Long getCurrentTime(String token){
        try{
            DecodedJWT decodedJWT=JWT.decode(token);
            return decodedJWT.getClaim(Const.CURRENT_TIME).asLong();

        }catch (JWTCreationException e){
            return null;
        }
    }
}
